package cn.xinfei.xdecision.data.core.frame.executors.collect.real;

import cn.xinfei.xdecision.common.model.datax.enums.CollectStageEnum;
import cn.xinfei.xdecision.data.core.frame.executors.collect.AbstractCollectService;
import cn.xinfei.xdecision.data.core.frame.executors.collect.VarHandlerChain;
import cn.xinfei.xdecision.data.core.frame.executors.collect.handler.*;
import cn.xinfei.xdecision.data.core.util.XyfPreConditions;
import cn.xinfei.xdecision.data.core.vo.VarCollectAwareVO;
import cn.xinfei.xdecision.model.VariableApiRequest;
import cn.xinfei.xdecision.model.VariableApiResponse;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Optional;

@Service
@Slf4j
public class RealCollectService extends AbstractCollectService implements IRealCollect {

    @Autowired
    VarDeriveDependParamHandler varDeriveDependParamHandler;
    @Autowired
    VarDispatchExecutorHandler varDispatchExecutorHandler;
    @Autowired
    VarRuteDataSourceHandler varRuteDataSourceHandler;
    @Autowired
    VarInputParamVerifyHandler varInputParamVerifyHandler;
    @Autowired
    VarBasicAndConstHandler varBasicAndConstHandler;
    @Autowired
    VarApiAndVariablesHandler varApiAndVariablesHandler;

    @Override
    public VariableApiResponse realCollect(VariableApiRequest variableApiRequest) {

        varCollectInputCheck(variableApiRequest);

        VarCollectAwareVO varCollectAwareVO = new VarCollectAwareVO();
        VariableApiResponse variableApiResponse = new VariableApiResponse();
        variableApiResponse.setRequestId(variableApiRequest.getRequestId());
        variableApiResponse.setStage(CollectStageEnum.REAL_TIME_COLLECT.name());


        varCollectAwareVO.setRequestId(variableApiRequest.getRequestId());
        varCollectAwareVO.setVarCodes(variableApiRequest.getVarCodes());
        varCollectAwareVO.setInputPrarams(variableApiRequest.getInputParams());

        VarHandlerChain varHandler = new VarHandlerChain();
        varHandler
                .addHandler(varDeriveDependParamHandler)
                .addHandler(varBasicAndConstHandler)
                .addHandler(varInputParamVerifyHandler)
                .addHandler(varApiAndVariablesHandler)
                .addHandler(varRuteDataSourceHandler)
                .addHandler(varDispatchExecutorHandler);

        varHandler.doHandle(varCollectAwareVO);
        variableApiResponse.setVariablesResponse(JSONObject.toJSONString(varCollectAwareVO.getExecutorResultMap(), SerializerFeature.WRITE_MAP_NULL_FEATURES,SerializerFeature.QuoteFieldNames));
        return variableApiResponse;
    }
}
